package hr.fer.zpr.nmbp.project2.dao;

import hr.fer.zpr.nmbp.project2.dao.exceptions.PrimaryKeyConstraintException;
import hr.fer.zpr.nmbp.project2.model.Bolest;
import hr.fer.zpr.nmbp.project2.model.Dijagnoza;

import java.util.List;
import java.util.Properties;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;

public class BolestDAO {

	private Session session;

    public BolestDAO(Session session) {
        this.session = session;
    }

	public void save(Bolest bolest) {
		if (bolest.getNaziv() == null || bolest.getNaziv().isEmpty()) {
			throw new PrimaryKeyConstraintException(
					"Naziv bolesti ne smije biti NULL");
		}
        
		Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.saveOrUpdate(bolest);
            tx.commit();
        } catch (ConstraintViolationException e) {
            if (tx != null) tx.rollback();
            throw new PrimaryKeyConstraintException("Sifra bolesti već postoji u bazi podataka");
        }
	}

	public void delete(final Bolest bolest) {
		Transaction tx = null;
        try {
            tx = session.beginTransaction();
            
            List<Dijagnoza> refDijagnoze = bolest.getDijagnoze();
            for(Dijagnoza dijag : refDijagnoze){
                dijag.getBolesti().remove(bolest);
                session.merge(dijag);
            }
            
            session.delete(bolest);
            tx.commit();
        } catch (Exception e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        }
	}

	public List<Bolest> load(Bolest bolestPrototype) {
		Properties prop = new Properties();
        StringBuilder sb = new StringBuilder();
        sb.append("select b from Bolest as b");
        if (bolestPrototype.getSifra() != null) {
            sb.append(" where b.sifra = :sifra");
            prop.put("sifra", bolestPrototype.getSifra());
        }
                                        
        return (List<Bolest>) session.createQuery(sb.toString()).setProperties(prop).list();
	}

	public List<Bolest> loadAll() {
		return (List<Bolest>) session.createQuery("select b from Bolest as b").list();
	}
}
